package com.gis.filter;

import java.util.Date;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.gis.bean.UserLog;
import com.gis.dao.LogDao;

import cn.hutool.core.map.MapUtil;
import cn.hutool.json.JSONUtil;


public class LogFilter implements Filter {
	LogDao logDao = LogDao.getInstance();

	@Override
	public void init(FilterConfig config) throws ServletException {
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws java.io.IOException, ServletException {
		HttpServletRequest httpServletRequest = (HttpServletRequest)request;
		String requestURI = httpServletRequest.getRequestURI();
		
		HttpSession session = httpServletRequest.getSession();
		String username = (String)session.getAttribute("username");
		if (username == null) {
			username = httpServletRequest.getParameter("username");
		}
		if (username == null) {
			username = "null";
		}
		
		Map<String, String[]> parameterMap = httpServletRequest.getParameterMap();
		// 因为parameterMap是不可变的，所以使用深拷贝将其复制到另一个Map中
		ConcurrentHashMap<String,String[]> params = MapUtil.newConcurrentHashMap(parameterMap);
		
		if(params.containsKey("password")) {
			params.remove("password");
		}
		
		// 如果用户访问的是jsp，则不记录日志
		  if (!requestURI.endsWith(".jsp")) { 
			  UserLog userLog = new UserLog();
			  userLog.setUsername(username); userLog.setUrl(requestURI);
			  userLog.setOprateTime(new Date());
			  userLog.setIp(httpServletRequest.getRemoteAddr()); 
			  userLog.setParams(JSONUtil.toJsonStr(params));
			  logDao.writeLog(userLog);
		  }
		 
		// 把请求传回过滤链
		chain.doFilter(request, response);
	}

	@Override
	public void destroy() {

	}
}